<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';

import { Page,z } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getPageInfo_news, postPage_news, putPage_news } from '#/api/portal/distributors';
import { usePreferencesStore } from '#/store';
import { useVbenModal } from '@vben/common-ui';


const index = ref<number>(0); // 外层定义
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  footer: false,
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values1: { id?: number } = formModalApi.getData();
      index.value = values1.id ?? 0; // 给外层的 index 赋值
      if(index.value>0){
             await onGetPage(index.value);
      }
      
    }
  },
 
});
const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

// const index: any = computed(() => {
//   return route.params?.id ?? -1;
// });
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
// const pageTitle =
//   Number.parseInt(index.value, 10) === 0
//     ? `新增${routeTitle}`
//     : `No.${index.value} - 编辑${routeTitle}`;
// setTabTitle(pageTitle);
// useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    company: '',
    tel: '',
    images: [],
  },
  pageThemeFiles: [],
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,

  resetButtonOptions: {
    show: false,
  },
  commonConfig: {
    labelWidth: 200,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.company;
          state.form.continents = values.continents;
          state.form.company = values.company;
          state.form.country = values.country;
          state.form.address = values.address;
          state.form.tel = values.tel;
          state.form.email = values.email;
          state.form.fax = values.fax;
          state.form.PIVA  = values.PIVA;
          state.form.images = values.images;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'continents',
          'company',
          'country',
          'address',
          'tel',
          'email',
          'images',
          'fax',
          'PIVA'
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'company',
      label: `${routeTitle} `+$t('admin.Company'),
      rules: 'required',
    },
    {
      component: 'Select',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Select'),
        class: 'w-full',
        options:[
            {
                label:'Asia',
                value:'Asia',
            },
            {
                label:'Africa',
                value:'Africa',
            },
            {
                label:'Europe',
                value:'Europe',
            },
            {
                label:'America',
                value:'America',
            },
            {
                label:'Oceania',
                value:'Oceania',
            }
        ],
      },
      fieldName: 'continents',
      label: `${routeTitle} `+$t('admin.continent'),
      rules: 'required',
    },

    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
        maxlength: 50, // ✅ 限制最多输入 50 个字符
      },
      fieldName: 'country',
      label: `${routeTitle} `+$t('admin.country'),
      rules: 'required',
    
    },

     {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'address',
      label: `${routeTitle} `+$t('admin.Address'),
      
    },

     {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'tel',
      label: `${routeTitle} `+$t('admin.Telephone'),
      rules:z.string().max(30,'电话不能超过30个字符')
    },


     {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'email',
      label: `${routeTitle} `+$t('admin.email'),
      rules: z.string().nonempty('邮箱不能为空').max(30, '邮箱不能超过 30 个字符').email('请输入正确的邮箱')
    },

     {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'fax',
      label: `${routeTitle} `+$t('admin.fax'),
    },
     {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'PIVA',
      label: `${routeTitle}PIVA`,
    },
    {
        component:'Upload',
            defaultValue: [{'url':'','id':''}],
            componentProps: {
                tips:'Scale:361X462px，size:100K 以内'
            },
            fieldName: 'images',
            label: `${routeTitle} `+$t('page.common.Image'),

    }

  ],
});



async function onSubmit() {
  const values: any = state.form;

  let response;

  if (values.id) {
    response = await putPage_news(values);
  } else {
    delete values.id;
    response = await postPage_news(values);
  }

  const { code, msg } = response;

  if (code === 1) {
    message.success(msg || '操作成功');
    // closeCurrentTab();
    // router.push({ name: 'Portaldistributors' });
     formModalApi.close();
    BasicFormApi.resetForm();
     state.form={};
    
  } else {
    message.error(msg || '操作失败'); 
  }
}




async function onGetPage(id: number) {
  const { data } = await getPageInfo_news({ id });
  data.post = {
    id: data?.id ?? undefined,
    company: data?.company ?? '',
    continents: data?.continents ?? '',
    country: data?.country ?? '',
    address: data?.address ?? '',
    tel: data?.tel ?? '',
    email: data?.email ?? '',
    fax: data?.fax ?? '',
    images:data?.images??[{'url':'','id':''}],
    PIVA:data?.PIVA??'',
  };
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
  state.pageThemeFiles = data.pageThemeFiles;
}

onMounted(async () => {
  if(index.value>0){
          await onGetPage(index.value);
  }
  
});
</script>

<template>
<Modal :title="state.form.title">
  <Page>
    <Card :title="`${routeTitle} `+$t('page.common.Details')">
      <BasicForm />
    </Card>
  </Page>
</Modal>

</template>
